// 要把登录请求的结果token存到vuex，所以把请求卸载vuex
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken, setTokenTime } from '@/utils/auth.js'
// import { remove } from 'js-cookie'
// user模块的数据
const state = {
  token: getToken(), // 用户token
  userInfo: {} // 存用户信息
}
// user模块数据修改的唯一途径
const mutations = {
  setToken(state, payload) {
    // 保存token到vuex
    state.token = payload
    // 保存到cookie
    setToken(payload)
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 清除Token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 清空用户
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 用户退出
  logout() {
    this.commit('user/removeToken')
    this.commit('user/removeUserInfo')
  }
}
const actions = {
  // 登录请求
  async login(context, data) {
    const res = await login(data)
    console.log(res)
    context.commit('setToken', res)
    setTokenTime()
  },
  // 获取用户资料
  async getUserInfo(context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId)
    const baseResult = { ...result, ...baseInfo }
    context.commit('setUserInfo', baseResult)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
